package ray.wx.util;

import java.sql.*;
import java.text.SimpleDateFormat;

public class MysqlUtil {
    private static final String driver = "com.mysql.jdbc.Driver";
    public static final String dbUrl = "jdbc:mysql://192.168.231.137:3306/weixin";
    public static final String dbUser = "root";
    public static final String dbPass = "root123";
    
    private String m_url;
    private String m_user;
    private String m_password;
    
    private Connection m_conn;
    private Statement m_statement;
    
    public MysqlUtil(String db_url, String db_user, String db_pass){
    	m_url = db_url;
    	m_user = db_user;
    	m_password = db_pass;
    }
    
    public void connect() throws ClassNotFoundException, SQLException {
    	//try {
			Class.forName(driver);
			
			m_conn = DriverManager.getConnection(m_url, m_user, m_password);
			
			m_conn.setAutoCommit(false);

			m_statement = m_conn.createStatement();
			
		//} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
		//	e.printStackTrace();
		//} catch (SQLException e) {
			// TODO Auto-generated catch block
		//	e.printStackTrace();
		//}
    }
    
    public void update_db(String sql){
    	try {
			m_statement.execute(sql);
			m_conn.commit();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
    }
    
    public int get_record_count(String sql){
    	try {
			ResultSet result_set = m_statement.executeQuery(sql);
			
			if (result_set.next()){
				return result_set.getInt("count(*)");
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
    	
    	return -1;
    }
    
    public static String get_cur_timestamp(){
        SimpleDateFormat sdf=new SimpleDateFormat("yyyyMMddhhmmssSSS"); 
        return sdf.format(System.currentTimeMillis());
    }
    
    public ResultSet get_record_value(String sql) throws SQLException {
		return m_statement.executeQuery(sql);
    }
}
